<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="服务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入服务名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <treeselect style="width:300px;" v-model="queryParams.categoryId" :options="categoryList" :show-count="true" placeholder="请选择分类" />
      </el-form-item>
       <el-form-item label="运营商" prop="operatorUserId" v-if="getoperatorfunc(this).userType != 1">
        <el-select v-model="queryParams.operatorUserId" placeholder="运营商" filterable clearable style="width: 200px">
          <el-option
            v-for="dict in operatorList"
            :key="dict.id"
            :label="dict.label"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="status" >
        <el-select v-model="queryParams.status" placeholder="服务状态" filterable clearable style="width: 200px">
          <el-option
            v-for="dict in dict.type.server_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格类型" prop="specType" >
        <el-select v-model="queryParams.specType" placeholder="规格类型" filterable clearable style="width: 200px">
          <el-option
            v-for="dict in dict.type.server_spec_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['trade:serverSpu:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="服务名称" align="center" prop="name"/>
      <el-table-column label="运营商名称" align="center" prop="operatorName" v-if="getoperatorfunc(this).userType != 1"/>
      <el-table-column label="分类名称" align="center" prop="categoryName"/>
      <el-table-column label="服务价格" align="center" prop="price"/>
      <el-table-column label="市场价" align="center" prop="marketPrice"/>
      <el-table-column label="成本价" align="center" prop="costPrice"/>
      <el-table-column label="虚拟销量" align="center" prop="virtualSalesCount"/>
      <el-table-column label="服务点击量" align="center" prop="browseCount"/>
      <el-table-column label="排序字段" align="center" prop="sort"/>
      <el-table-column label="规格类型" align="center" prop="specType">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.server_spec_type" :value="row.specType" />
        </template>
      </el-table-column>
      <el-table-column label="服务状态" align="center" key="status">
        <template slot-scope="{row}">
          <el-switch v-if="upDateStatusFlag"
          v-model="row.status"
          :active-value="1" :inactive-value="0"
          @change="handleStatusChange(row)"></el-switch>
          <dict-tag :options="dict.type.server_status" v-else :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(row)"
            v-hasPermi="['trade:serverSpu:edit']">修改
          </el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)"
            v-hasPermi="['trade:serverSpu:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        
        <el-row >
          <el-col :span="24" >
            <div class="dialog_title flex_hcneter">基础信息</div>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="服务名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入服务名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="form.keyword" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="分类" prop="categoryId">
              <treeselect v-model="form.categoryId" :options="categoryList" :show-count="true" placeholder="请选择分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="运营商" prop="operatorUserId" v-if="getoperatorfunc(this).userType != 1 && !form.id">
              <el-select v-model="form.operatorUserId" placeholder="运营商" filterable clearable style="width:100%;">
                <el-option
                  v-for="dict in operatorList"
                  :key="dict.id"
                  :label="dict.label"
                  :value="Number(dict.id)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="封面图地址" prop="coverPicUrl">
              <imageUpload v-model="form.coverPicUrl" :limit="1"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="轮播图地址" prop="bannerPicUrls">
              <imageUpload v-model="form.bannerPicUrls" :limit="100"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item  label="视频地址" prop="bannerVideoUrls">
              <FileUpload :limit="100"  v-model="form.bannerVideoUrls" accept=".mp4,.mp3" :fileType="['mp4','mp3']" :fileModel="2" fileName="files" ></FileUpload>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="服务状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in dict.type.server_status"
                :key="item.value"
                :label="Number(item.value)">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="服务简介" prop="introduction">
              <el-input type="textarea" v-model="form.introduction" :rows="6" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24" >
            <el-form-item label="服务详情" prop="description">
              <editor v-model="form.description" :min-height="192"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="24" >
            <el-form-item label="服务详情" prop="description">
              <imageUpload v-model="form.description" :limit="100"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <div class="dialog_title flex_hcneter">服务信息</div>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="服务价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="市场价" prop="marketPrice">
              <el-input-number v-model="form.marketPrice" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="虚拟销量" prop="virtualSalesCount">
              <el-input-number v-model="form.virtualSalesCount" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="规格类型" prop="specType">
              <el-radio-group v-model="form.specType">
                <el-radio v-for="item in dict.type.server_spec_type"
                :key="item.value"
                :label="Number(item.value)">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <h2>商品规格：<el-button type="primary" v-if="form.specType == 1" icon="el-icon-plus" @click="addList()">添加新规格</el-button></h2>
          </el-col>
        </el-row>
        <div v-if="form.specType == 1">
          <el-row v-for="(item,index) in skuList" :key="index" style="margin-bottom:15px;">
            <el-col :span="24" style="background-color:#EFF2F5;width:100%;padding:10px;position: relative;">
              <div class="del_close flex_zhcenter" @click="delList(index)"><i class="el-icon-close"></i></div>
              <el-col :span="24" >
                <el-form-item label="规格名称：">
                  <el-select v-model="item.propertyId" @change="(e)=>sxChange(e,item)" placeholder="属性" filterable clearable style="width: 200px">
                    <el-option :disabled="getTypeStatus(dict.id,index)"
                      v-for="dict in shuxingList"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" >
                <el-form-item label="规格值：">
                  <el-tag v-for="(item1,index1) in item.shuxingValueList" :key="index1" style="margin-right:10px;"
                      :closable="scsxzFlag" :disable-transitions="false" @close="delList(index,item,item1)">{{item1.name || item1.valueName}}</el-tag>
                      <el-link type="primary" v-if="item.propertyId" icon="el-icon-plus" @click="addList(item,index)" :underline="false">添加规格</el-link>
                </el-form-item>
              </el-col>
            </el-col>
          </el-row>
          <el-row style="margin-bottom:15px;">
            <el-col :span="24" >
              <!-- 规格明细表格数据 -->
              <el-table :data="skuMxList">
                <el-table-column label="序号" align="center" type="index"/>
                <el-table-column label="规格组合" align="center" prop="valueNameStrs"/>
                <el-table-column label="价格" align="center" prop="price">
                  <template slot-scope="{row}">
                    <el-input-number v-model="row.price" :precision="2" :step="1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="市场价" align="center" prop="marketPrice">
                  <template slot-scope="{row}">
                    <el-input-number v-model="row.marketPrice" :precision="2" :step="1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="成本价" align="center" prop="costPrice">
                  <template slot-scope="{row}">
                    <el-input-number v-model="row.costPrice" :precision="2" :step="1" :min="0"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="规格图片" align="center" prop="picUrl">
                  <template slot-scope="{row}">
                    <imageUpload v-model="row.picUrl" :limit="1"></imageUpload>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="{row,$index},">
                    <el-button type="text" icon="el-icon-delete" @click="handleSkuDelete(row,$index)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>
        <div v-if="form.specType == 0">
          <el-row v-for="(item,index) in form.skus" :key="index">
            <el-col :span="12" >
              <el-form-item label="服务价格">
                <el-input-number v-model="item.price" :precision="2" :step="1" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="市场价">
                <el-input-number v-model="item.marketPrice" :precision="2" :step="1" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="成本价">
                <el-input-number v-model="item.costPrice" :precision="2" :step="1" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24" >
              <el-form-item label="选择图片">
                <imageUpload v-model="item.picUrl" :limit="1"></imageUpload>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24" >
              <el-form-item label="选择属性：">
                <el-button type="primary" icon="el-icon-plus" @click="addList(index)" ></el-button>
                <el-button type="primary" icon="el-icon-minus" @click="delList(index)" v-if="form.skus.length > 1"></el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-for="(item1,index1) in item.properties" :key="index1">
              <el-col :span="12" >
                <el-form-item label="属性" prop="propertyId">
                  <el-select v-model="item1.propertyId" @change="(e)=>sxChange(e,item1)" placeholder="属性" filterable clearable style="width: 200px">
                    <el-option :disabled="getTypeStatus(dict.id,index,index1)"
                      v-for="dict in shuxingList"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" >
                <el-form-item label="属性值" prop="valueId">
                  <div class="flex_hcneter">
                    <el-select
                    v-model="item1.valueId" placeholder="属性值" filterable clearable style="width: 200px">
                      <el-option
                        v-for="dict in item1.shuxingValueList"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                      />
                    </el-select>
                    <el-button type="primary" @click="delList(index,index1)" v-if="item.properties.length > 1" icon="el-icon-minus" style="margin-left:10px;"></el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-col> -->

          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="popLodding" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title1" :visible.sync="open1" width="80%" append-to-body>
      <el-form ref="formRef1" :model="form1" :rules="rules1" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form1.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="6" v-model="form1.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="popLodding1" @click="submitForm1">确 定</el-button>
        <el-button @click="open1 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/commodity/serverSpu";
import { treeListServerCategory } from "@/api/commodity/serviceClass";
import { listAllOperator } from "@/api/operator/operatorList";
import { listAllServerProperty } from "@/api/commodity/serviceAttribute";
import { listAllServerPropertyValue,addServerPropertyValue,delServerPropertyValue,} from "@/api/commodity/serviceAttribValue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
name: "ServerSpu",
dicts: ['server_status','server_spec_type',],
components: { Treeselect, },
data() {
  return {
    popLodding:false,//弹窗1加载
    popLodding1:false,//弹窗2加载
    form:{},
    form1:{},
    // 弹出层标题
    title: "",
    title1: "",
    // 是否显示弹出层
    open: false,
    open1: false,
    // 遮罩层
    loading: true,
    // 显示搜索条件
    showSearch: true,
    queryParams: {// 查询参数
      pageNum: 1,name:null,categoryId:null,
      pageSize: 10,status:null,specType:null,operatorUserId:null,
    },
    // 总条数
    total: 0,
    rules: {
      operatorUserId: [{required: true, message: "运营商不能为空", trigger: "change"}],
      name: [{required: true, message: "服务名称不能为空", trigger: "blur"}],
      keyword: [{required: true, message: "关键字不能为空", trigger: "blur"}],
      introduction: [{required: true, message: "服务简介不能为空", trigger: "blur"}],
      description: [{required: true, message: "服务详情不能为空", trigger: "blur"}],
      categoryId: [{required: true, message: "服务分类不能为空", trigger: "change"}],
      coverPicUrl: [{required: true, message: "封面图地址不能为空", trigger: "change"}],
      bannerPicUrls: [{required: true, message: "轮播图地址不能为空", trigger: "change"}],
      sort: [{required: true, message: "排序字段不能为空", trigger: "blur"}],
      status: [{required: true, message: "服务状态不能为空", trigger: "change"}],
      specType: [{required: true, message: "规格类型不能为空", trigger: "change"}],
      price: [{required: true, message: "服务价格不能为空", trigger: "blur"}],
      marketPrice: [{required: true, message: "市场价不能为空", trigger: "blur"}],
      costPrice: [{required: true, message: "成本价不能为空", trigger: "blur"}],
      virtualSalesCount: [{required: true, message: "虚拟销量不能为空", trigger: "blur"}],
    },
    rules1: {
      name: [{required: true, message: "名称不能为空", trigger: "blur"}],
    },
    list:[],//页面数据
    operatorList:[],//运营商数据
    categoryList:[],//分类数据
    shuxingList:[],//属性项数据
    shuxingValueList:[],//属性值数据
    properties:{shuxingValueList:[],propertyId:null,valueId:null,},
    xgztPermissions:'trade:serverSpu:updateStatus',//修改状态权限
    scsxzPermissions:'trade:serverPropertyValue:remove',//删除属性值权限
    upDateStatusFlag:false,//修改状态显示
    scsxzFlag:false,//删除属性值显示
    skuList:[],
    skuMxList:[],
    updateFlag:1,
  };
},
created() {
  const user = this.$store.state.user
  const permissions = user.permissions
  const flag = !!permissions.find(item => item == this.xgztPermissions)
  if( flag || permissions[0] == '*:*:*' ) this.upDateStatusFlag = true
  const flag1 = !!permissions.find(item => item == this.scsxzPermissions)
  if( flag1 || permissions[0] == '*:*:*' ) this.scsxzFlag = true
  this.treeListServerCategory()
  this.listAllOperator()
  this.getList()
},
watch:{
  skuList:{
    handler(val) {
      console.log('watch',val)
      this.guigemingxi(val)
    },
    deep: true// 开启深度监听
  },
},
methods: {
  handleSkuDelete(e,index){//删除sku
    this.skuMxList.splice(index,1)
  },
  guigemingxi(val){
    let skuList = val.filter(item=>item.propertyId)
    let leng = 0
    let skus = []
    skuList.map((item,index)=>{
      let shuxingValueList = item.shuxingValueList || []
      shuxingValueList = shuxingValueList.map(item1=>{
        return {
          valueName:item1.name || item1.valueName,
          ...item1,propertyName:item.propertyName,
        }
      })
      if(index == 0) {
        leng = shuxingValueList.length
      } else{
        leng = leng * shuxingValueList.length
      }
      skus[index] = shuxingValueList
    })
    console.log('skus',skus)
    if(leng) {
      this.strs = []
      this.skusReturn = []
      let index5 = 0
      // skus[0].map((item,index)=>{
      //   if(skus.length > 1) {
      //     for (let j = 1; j < skus.length; j++) {
      //       // 组合两个字符和三个字符，并添加到数组中
      //       console.log('skus[j]',skus[j],j)
            
      //       skus[j].map(item1=>{
      //         console.log('index5',index5)
      //         let lists = strs[index5] || []
      //         if(!lists.length) strs[index5] = [item]
      //         console.log('strs[index5]1',strs[index5])
      //         strs[index5] = strs[index5].concat(item1)
      //         console.log('strs[index5]2',strs[index5])
      //         index5 +=1
      //       })
      //     }
      //   }else{
      //     strs[index5] = [item]
      //     index5 +=1
      //   }
      // })
      skus.map((item,index)=>{
        this.getskusLIst(item,index,this.strs,skus,index5)
      })
      // console.log('strs5',strs)
    }else{
      this.skusReturn = []
    }
    return leng ? this.skusReturn : []
  },
  getskusLIst(e,index,strs,skus,index5){
    console.log('getskusLIst',e,index,this.strs,skus,index5)
    let list = this.$copyValue(this.strs)
    if(index > 0) {
      this.strs.map((item,index1)=>{
        e.map(item1=>{
          list[index5] = item.concat([item1])
          index5 += 1
        })
      })
      this.strs = this.$copyValue(list)
    }else{
      e.map(item1=>{
        this.strs[index5] = [item1]
        index5 += 1
      })
    }
    this.skusReturn = this.strs.map(item3=>{ return {properties:item3,} })
    this.skuMxList = this.skusReturn.map(item4=>{ 
      let valueNameStrs = ''
      let properties = item4.properties || []
      properties = properties.map((item5,index5)=>{
        valueNameStrs += item5.name + (index5 == properties.length - 1 ? '' : '-')
        return {...item5,valueName:item5.name,valueId:item5.id,}
      })
      return {
        ...item4,
        valueNameStrs,
        properties,
      } 
    })
    if(this.form.id && this.updateFlag === 2 && index == skus.length - 1) {
      this.skuMxList = this.$copyValue(this.form.skus)
      this.updateFlag = 1
      console.log(3333)
    }
    console.log('this.skuMxList',this.skuMxList)
    console.log('strs5',this.strs)
  },
  // 状态修改
  handleStatusChange(row) {
    let text = row.status === 1 ? "上架" : "下架";
    this.$modal.confirm(`确认要${text}该数据吗？`).then(function() {
      return api.updateStatus({status:row.status,id:row.id,});
    }).then(() => {
      this.$modal.msgSuccess(text + "成功");
      this.getList()
    }).catch(()=> {
      row.status = row.status === 1 ? 0 : 1;
    });
  },
  getTypeStatus(value,index){//禁用选项
    // let properties = this.form.skus[index].properties || []
    // return properties.find((item,indexs)=>item.propertyId == value && indexs != index1 ) ? true : false
    let skuList = this.skuList || []
    return skuList.find((item,indexs)=>item.propertyId == value && indexs != index ) ? true : false
  },
  addList(e,index){//添加列表
    // if(index === 0 || index){
    //   let properties = this.form.skus[index].properties || []
    //   properties.push( {...this.properties} )
    //   this.form.skus[index].properties = this.$copyValue(properties)
    // }else{
    //   this.form.skus.push({ properties:[{...this.properties}] })
    // }
    if(e){
      this.reset1()
      this.open1 = true
      this.title1 = "添加服务属性值";
      this.form1 = {propertyId:e.propertyId,index,}
    }else{
      this.skuList.push({ shuxingValueList:[], })
    }
  },
  delList(index,e,e1){//删除列表
    // if(index1 === 0 || index1){
    //   let properties = this.form.skus[index].properties || []
    //   properties.splice(index1,1)
    //   this.form.skus[index].properties = this.$copyValue(properties)
    // }else{
    //   this.form.skus.splice(index,1)
    // }
    if(e){
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delServerPropertyValue(e1.id);
      }).then(async () => {
        this.$modal.msgSuccess("删除成功");
        e.shuxingValueList = await this.listAllServerPropertyValue(e.propertyId)
      }).catch(() => {});
    }else{
      this.skuList.splice(index,1)
    }
  },
  async sxChange(e,item){//属性改变
    // item.valueId = null
    // item.shuxingValueList = await this.listAllServerPropertyValue(e)
    let obj = this.shuxingList.find(item1=>item1.id == e)
    item.propertyName = obj ? obj.name : null
    item.shuxingValueList = await this.listAllServerPropertyValue(e)
  },
  async listAllServerPropertyValue(propertyId){//属性值列表
    let res = await listAllServerPropertyValue({propertyId})
    let data = res.data || []
    this.shuxingValueList = data
    return data
  },
  async listAllServerProperty(){//属性项列表
    let res = await listAllServerProperty()
    let data = res.data || []
    this.shuxingList = data.map(item=>{
      return {
        ...item,shuxingValueList:[],
      }
    })
  },
  async treeListServerCategory(){//查询分类树列表
    let res = await treeListServerCategory()
    let data = res.data || []
    this.categoryList = data
    this.findChild(this.categoryList)
  },
  findChild(list){//找到是否存在
    list.forEach(item=>{
      item.label = item.name
      let children = item.children || []
      if(children.length){
        this.findChild(children)
      }else{
        delete item.children
      }
    })
  },
  async listAllOperator(){//获取运营商
    let res =await listAllOperator()
    let data = res.data || []
    this.operatorList = data
  },
  getList() {
    this.loading = true;
    api.listServerSpu(this.queryParams).then(response => {
      let rows = response.rows || [];
      this.list = rows.map(item=>{
        return{...item,...this.getpricezh(item),}
      })
      this.total = response.total || 0;
      this.loading = false;
    });
  },
  handleAdd() {
    this.open = true;
    this.reset();
    this.skuList = [{shuxingValueList:[],}]
    this.title = "添加服务spu";
  },
  handleUpdate(row) {
    this.reset();
    const id = row.id || this.ids;
    this.open = true;
    this.title = "修改服务spu";
    api.getServerSpu(id).then(response => {
      let data = response.data || {}
      let skus = data.skus || []
      let specType = data.specType
      this.skuArr = []
      this.updateFlag = 2
      skus = skus.map(item=>{
        let valueNameStrs = ''
        let properties = item.properties || [{...this.properties}]
        return {
          ...item,
          properties:properties.map((item1,index1)=>{
            valueNameStrs += (item1.valueName || '') + (index1 == properties.length - 1 ? '' : '-')
            return {...item1,shuxingValueList:item1.shuxingValueList || [],}
          }),
          valueNameStrs,
          price:this.math.divide(item.price || 0,100),
          marketPrice:this.math.divide(item.marketPrice || 0,100),
          costPrice:this.math.divide(item.costPrice || 0,100),
        }
      })
      this.form = {
        ...data,...this.getpricezh(data),
        skus,
      };
      if(specType == 1) {
        skus.map(item=>{
          item.properties.map(item1=>{
            if(specType == 1) {
              let obj = this.skuArr.find(item2=>item2.propertyId == item1.propertyId)
              if(!obj) {
                this.skuArr.push({
                  propertyName:item1.propertyName,
                  propertyId:item1.propertyId,shuxingValueList:item.properties,
                })
              }
            }
          })
        })
        console.log('skuList777',this.skuArr)
        console.log(this.skuList,'this.skuList989')
        this.skuArr.map((item,index)=>{
          this.listAllServerPropertyValue1(item,index,this.skuArr)
        })
      }
      
    });
  },
  async listAllServerPropertyValue1(item,index,skuList){//属性值列表
    let res = await listAllServerPropertyValue({propertyId:item.propertyId})
    let data = res.data || []
    this.skuArr[index].shuxingValueList = data.map(item1=>{
      return {
        ...item1,name:item1.valueName || item1.name,
        valueName:item1.valueName || item1.name,
      }
    })
    if(this.skuArr.length -1 === index) {
      this.skuList = this.skuArr.map(item=> {
        return {...item}
      })
      console.log(this.skuArr,'listAllServerPropertyValue1')
      console.log(this.skuList,'listAllServerPropertyValue1')
      this.$forceUpdate()
    }
  },
  getpricezh(item){//字段转换
    return {
      price:this.math.divide(item.price || 0,100),
      marketPrice:this.math.divide(item.marketPrice || 0,100),
      costPrice:this.math.divide(item.costPrice || 0,100),
    }
  },
  submitForm() {
    this.$refs["formRef"].validate(valid => {
      if (valid) {
        let form = {...this.form}
        if(this.getoperatorfunc(this).operatorUserId) delete form.operatorUserId
        form.price = this.math.multiply(form.price || 0,100)
        form.marketPrice = this.math.multiply(form.marketPrice || 0,100)
        form.costPrice = this.math.multiply(form.costPrice || 0,100)
        let skus = []
        
        let flag = ''
        if(form.specType == 1) {
          skus = this.skuMxList || []
          let skuList = this.skuList || []
          let skuPropertyIds = []
          skuList.map(item=>{
            skuPropertyIds.push(item.propertyId)
          })
          form.skuPropertyIdStr = skuPropertyIds.toString()
          
          form.skus = skus.map((item,index)=>{
            if( this.$getNull(item.price) || this.$getNull(item.marketPrice) || this.$getNull(item.costPrice) || this.$getNull(item.picUrl) ) flag = `请填写完整商品规格`
            let properties = item.properties || []
            item.properties = properties.map((item1,index1)=>{
              if( this.$getNull(item1.propertyId) || this.$getNull(item1.valueId) ) flag = `请填写完整商品规格`
              let obj = this.shuxingList.find(item3=>item3.id == item1.propertyId)
              let shuxingValueList = item1.shuxingValueList || []
              let obj1 = shuxingValueList.find(item3=>item3.id == item1.valueId)
              return {
                ...item1,
                propertyName:obj ? obj.name : '',valueName:obj1 ? obj1.name : (item1.valueName || item1.name || ''),
              }
            })
            return {
              ...item,
              price:this.math.multiply(item.price || 0,100),marketPrice:this.math.multiply(item.marketPrice || 0,100),
              costPrice:this.math.multiply(item.costPrice || 0,100),
            }
          })
          console.log('submitForm',skus)
          console.log('submitForm',form.skus)
          if(flag) return this.$modal.msgError(flag)
        }else{
          skus = [...form.skus]
          form.skus = skus.map((item,index)=>{
            if( this.$getNull(item.price) || this.$getNull(item.marketPrice) || this.$getNull(item.costPrice) || this.$getNull(item.picUrl) ) flag = `请填写完整商品规格`
            delete item.properties
            return {
              ...item,
              price:this.math.multiply(item.price || 0,100),marketPrice:this.math.multiply(item.marketPrice || 0,100),
              costPrice:this.math.multiply(item.costPrice || 0,100),
            }
          })
        }
        
        this.popLodding = true
        if (this.form.id != undefined) {
          api.updateServerSpu(form).then(response => {
            this.popLodding = false
            this.$modal.msgSuccess("修改成功")
            this.open = false;
            this.getList();
          }).catch(error=>this.popLodding = false);
        } else {
          api.addServerSpu(form).then(response => {
            this.popLodding = false
            this.$modal.msgSuccess("新增成功")
            this.open = false;
            this.getList()
          }).catch(error=>this.popLodding = false);
        }
      }
    });
  },
  submitForm1() {
    this.$refs["formRef1"].validate(valid => {
      if (valid) {
        let form1 = {...this.form1}
        this.popLodding1 = true
        addServerPropertyValue(form1).then(async response => {
          this.popLodding1 = false
          this.$modal.msgSuccess("新增成功")
          this.open1 = false;
          let skuList = this.$copyValue(this.skuList)
          skuList[this.form1.index].shuxingValueList = await this.listAllServerPropertyValue(this.form1.propertyId)
          this.skuList = this.$copyValue(skuList)
        }).catch(error=>this.popLodding1 = false);
      }
    });
  },
  // 表单重置
  reset() {
    this.form = {
      status:1,
      operatorUserId:this.getoperatorfunc(this).operatorUserId,
      specType:0,skus:[{ properties:[{...this.properties}] }],
      skuList:[{shuxingValueList:[],}],//多规格sh
    };
    this.skuMxList = []
    this.resetForm("formRef");
    this.treeListServerCategory()
    this.listAllServerProperty()
    this.listAllOperator()
  },
  reset1() {
    this.form1 = {
    };
    this.resetForm("formRef1");
  },
  /** 搜索按钮操作 */
  handleQuery() {
    this.queryParams.pageNum = 1;
    this.getList();
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.resetForm("queryForm");
    this.handleQuery();
  },
  handleDelete(row) {//删除
    const del_ids = row.id || this.ids;
    this.$modal.confirm('是否确认删除该数据项？').then(function() {
      return api.delServerSpu(del_ids);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  },
}
};
</script>
<style lang="scss" scoped>
.del_close{
  width: 16px;height: 16px;border-radius: 50%;background-color: #C4CBD4;
  position: absolute;right: -6px;top: -6px;color: #fff;font-size: 12px;cursor: pointer;
}
.dialog_title{
  font-size: 22px;font-weight: bold;height: 22px;margin-bottom: 15px;
  border-left: 4px solid salmon;padding-left: 10px;
}
</style>